<template>
  <div class="borrow-list">
    <n-card>
      <n-space vertical>
        <n-space justify="space-between">
          <n-space>
            <n-select
              v-model:value="searchParams.status"
              :options="statusOptions"
              placeholder="选择状态"
              clearable
              style="width: 150px;"
              @update:value="handleSearch"
            />
            <n-select
              v-if="userStore.isAdmin"
              v-model:value="searchParams.userId"
              :options="userOptions"
              placeholder="选择用户"
              clearable
              filterable
              style="width: 200px;"
              @update:value="handleSearch"
            />
          </n-space>
          <h2>{{ userStore.isAdmin ? '借阅记录管理' : '我的借阅记录' }}</h2>
        </n-space>
        
        <n-data-table
          :columns="columns"
          :data="records"
          :loading="loading"
          :pagination="pagination"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>
  </div>
</template>

<script setup>
import { ref, h, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { borrowApi } from '@/api/borrow'
import { userApi } from '@/api/user'
import { 
  NCard, NSpace, NSelect, NDataTable, NTag, NButton, NPopconfirm, useMessage 
} from 'naive-ui'

const userStore = useUserStore()
const message = useMessage()

const loading = ref(false)
const records = ref([])
const userOptions = ref([])

const searchParams = ref({
  status: null,
  userId: null,
  current: 1,
  size: 10
})

const pagination = ref({
  page: 1,
  pageSize: 10,
  pageCount: 1,
  itemCount: 0
})

const statusOptions = [
  { label: '借出中', value: 'BORROWED' },
  { label: '已归还', value: 'RETURNED' },
  { label: '已逾期', value: 'OVERDUE' }
]

const getStatusType = (status) => {
  const map = {
    BORROWED: 'info',
    RETURNED: 'success',
    OVERDUE: 'error'
  }
  return map[status] || 'default'
}

const getStatusText = (status) => {
  const map = {
    BORROWED: '借出中',
    RETURNED: '已归还',
    OVERDUE: '已逾期'
  }
  return map[status] || status
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const columns = [
  ...(userStore.isAdmin ? [{ title: '用户', key: 'username' }] : []),
  { title: '图书', key: 'bookTitle' },
  { title: '作者', key: 'bookAuthor' },
  { 
    title: '借阅日期', 
    key: 'borrowDate',
    render: (row) => formatDate(row.borrowDate)
  },
  { 
    title: '应还日期', 
    key: 'dueDate',
    render: (row) => formatDate(row.dueDate)
  },
  { 
    title: '归还日期', 
    key: 'returnDate',
    render: (row) => formatDate(row.returnDate)
  },
  { 
    title: '续借次数', 
    key: 'renewCount'
  },
  { 
    title: '罚金', 
    key: 'fine',
    render: (row) => row.fine > 0 ? `¥${row.fine}` : '-'
  },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => h(NTag, { type: getStatusType(row.status) }, () => getStatusText(row.status))
  },
  {
    title: '操作',
    key: 'actions',
    render: (row) => {
      if (row.status === 'BORROWED' || row.status === 'OVERDUE') {
        return h(NSpace, null, () => [
          row.renewCount < 2 && h(NButton, {
            size: 'small',
            onClick: () => handleRenew(row.id)
          }, () => '续借'),
          h(NPopconfirm, {
            onPositiveClick: () => handleReturn(row.id)
          }, {
            trigger: () => h(NButton, { size: 'small', type: 'primary' }, () => '归还'),
            default: () => '确定归还这本图书吗？'
          })
        ])
      }
      return '-'
    }
  }
]

const loadRecords = async () => {
  loading.value = true
  try {
    const params = { ...searchParams.value }
    const data = userStore.isAdmin 
      ? await borrowApi.getRecords(params)
      : await borrowApi.getMyRecords(params)
    
    records.value = data.records
    pagination.value = {
      page: data.current,
      pageSize: data.size,
      pageCount: data.pages,
      itemCount: data.total
    }
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const loadUsers = async () => {
  if (!userStore.isAdmin) return
  try {
    const data = await userApi.getUsers({ current: 1, size: 1000 })
    userOptions.value = data.records.map(u => ({ label: u.username, value: u.id }))
  } catch (error) {
    console.error(error)
  }
}

const handleSearch = () => {
  searchParams.value.current = 1
  loadRecords()
}

const handlePageChange = (page) => {
  searchParams.value.current = page
  loadRecords()
}

const handleRenew = async (recordId) => {
  try {
    await borrowApi.renewBook(recordId)
    message.success('续借成功')
    loadRecords()
  } catch (error) {
    console.error(error)
  }
}

const handleReturn = async (recordId) => {
  try {
    await borrowApi.returnBook(recordId)
    message.success('归还成功')
    loadRecords()
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  loadRecords()
  loadUsers()
})
</script>

